var form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id");
let loginUserCode = user.code;//当前登录用户编码

layui.use(['tableEdit'], function () {
    let colourList = getdictionary(6, 41);//颜色
    let unitList = getdictionary(6, 42);//单位

    let productList = [];
    let fileList = [];
    let wjCatalogCode = "CustomerComplaint";//文件编码
    let logList = [
        {
            id: "1",
            operationtype: "text1",
            theoperator: "text2",
            operationdate: "text3",
            modifythecontent: "text4"
        }
    ];

    let complaintUnitList = [];
    //制单公司
    $.ajax({
        url: "company/getAllMakerUnit",
        success: function (res) {
            if (res.status == 200) {
                $.each(res.data, function (index, item) {
                    $("#complaintUnit").append(new Option(item.name, item.code));
                });
                form.render('select');
                complaintUnitList = res.data;
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });

    let executorList = [];
    //获取当前登陆用户名称
    $.ajax({
        url: "user/getAllUserNameAndCode",
        success: function (res) {
            if (res.status == 200) {
                executorList = res.data;
                $.each(res.data, function (index, item) {
                    $("#executor").append(new Option(item.name, item.code));
                    $("#salesman").append(new Option(item.name, item.code));
                });
                if (id != "") {
                    queryById();
                } else {
                    $("#executor").val(loginUserCode);
                    $("#salesman").val(loginUserCode);
                }
                form.render('select');
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });


    let currencyList = getdictionary(5, 14);//币种列表
    for (let i in currencyList) {
        $('#currency').append(new Option(currencyList[i].name, currencyList[i].code));
    }
    let issuingBankList = [];//银行列表
    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

//表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "executor": "进入修改",
        })
        $("#oddNumber").attr("readonly", true);
    } else {
        laydate.render({
            elem: '#createTime',
            type: 'date',
            value: new Date(),
        });
        $.ajax({
            type:'POST',
            url:'complaint/getLatestOddNumber',
            dataType:"json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data != "") {
                        form.val("editor-form", {
                            "oddNumber": res.data,
                        })
                    }
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            },
            error: function (data) {
                layer.msg(data.msg, {icon: 5});
            }
        })
        // let dataJson = {
        //     "type": "KS",
        // };
        // $.ajax({
        //     type: 'POST',
        //     url: 'number/numberByTypeAndDate',
        //     data: JSON.stringify(dataJson),
        //     dataType: "json",
        //     contentType: 'application/json;charset=utf-8',
        //     async: false,
        //     success: function (res) {
        //         if (res.status == 200) {
        //             if (res.data != "") {
        //                 form.val("editor-form", {
        //                     "oddNumber": res.data,
        //                 })
        //             }
        //         } else {
        //             layer.msg(res.msg, {icon: 5});
        //         }
        //     },
        //     error: function (data) {
        //         layer.msg(data.msg, {icon: 5});
        //     }
        // });
    }

//监听提交
    form.on('submit(form-element)', function (data) {
        let indexsl = 0;
        let productCache = table.cache["storageproductstableid"];
        // $.each(productCache, function (index, value) {
        //     if (typeof (productCache[index]["unit"]) == "undefined" || productCache[index]["unit"] == "") {
        //         layer.msg("客诉明细表第" + (index + 1) + "条单位未选择");
        //         indexsl++;
        //         return false;
        //     } else if (typeof (productCache[index]["colour"]) == "undefined" || productCache[index]["colour"] == "") {
        //         layer.msg("客诉明细表第" + (index + 1) + "条颜色未选择");
        //         indexsl++;
        //         return false;
        //     } else if (typeof (productCache[index]["amount"]) == "undefined" || productCache[index]["amount"] == "") {
        //         layer.msg("客诉明细表第" + (index + 1) + "条数量不可为 0");
        //         indexsl++;
        //         return false;
        //     } else if (typeof (productCache[index]["price"]) == "undefined" || productCache[index]["price"] == "") {
        //         layer.msg("客诉明细表第" + (index + 1) + "条单价不可为 0");
        //         indexsl++;
        //         return false;
        //     }
        //     if (typeof (productCache[index]["priceSubtotal"]) == "undefined" || productCache[index]["priceSubtotal"] == "") {
        //         layer.msg("客诉明细表第" + (index + 1) + "条小计不可为 0");
        //         indexsl++;
        //         return false;
        //     }
        // });

        if (indexsl == 0) {
            let flag = false;
            let reqData = data.field;
            reqData["productList"] = productCache;
            reqData["fileList"] = fileList;
            if (id == "") {
                flag = insert(reqData);
            } else {
                reqData.id = id;
                flag = update(reqData);
            }
            if (flag) {
                layer.msg("保存成功", {icon: 6});
                setTimeout(function () {
                    //保存成功则刷新提交过来的界面 并关闭此页面
                    parent.detab("views/jsp/other/customercomplaint.jsp");
                    parent.intab("views/jsp/other/customercomplaint.jsp", "客诉")
                    parent.detab("views/jsp/other/tpl/newupcustomercomplaint.jsp" + (id == '' ? '' : '?id=' + id));
                }, 1000);
            } else {
                layer.msg("保存失败", {icon: 5});
            }
        }
        return false;
    });

//--客诉明细
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: productList,
        toolbar: '#storageproductstoolbar',
        cellMinWidth: 120,
        cols: [[
            {checkbox: true},
            {field: 'productimg', title: '图片', align: 'center', templet: '#imgTpl'},
            {field: 'customerArticleNo', title: '销售合同号', sort: true,style:"overflow:hidden"},
            {field: 'productNo', title: '产品编码', sort: true,style:"overflow:hidden"},
            {field: 'specNo', title: '规格编码', sort: true,style:"overflow:hidden"},
            {field: 'normExplain', title: '规格说明',style:"overflow:hidden"},
            {field: 'customerArticleNo', title: '客户货号', sort: true,style:"overflow:hidden"},
            {field: 'chineseName', title: '中文名称',style:"overflow:hidden"},
            {field: 'englishName', title: '英文名称',style:"overflow:hidden"},
            {field: 'chineseDesc', title: '中文描述',style:"overflow:hidden"},
            {field: 'englishDesc', title: '英文描述',style:"overflow:hidden"},
            {field: 'unit', title: '单位'/*, templet: '#unitScript'*/,
                templet: function(data) {
                    let name = "";
                    $.each(unitList, function(index, item) {
                        if (data.unit==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    if(data.unit){
                        if(name==""){
                            name = data.unit;
                        }
                    }
                    return name;
                },
            },
            {field: 'colour', title: '颜色'/*, templet: '#colourScript'*/,
                templet: function(data) {
                    let name = "";
                    $.each(colourList, function(index, item) {
                        if (data.colour==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    if(data.colour){
                        if(name==""){
                            name = data.colour;
                        }
                    }
                    return name;
                }
            },
            {field: 'price', title: '单价', edit: 'text',
                templet: function (d) {
                    return d.price?Number(d.price).toFixed(4):Number(0).toFixed(4);
                }
            },
            {field: 'amount', title: '数量', edit: 'text',
                templet: function (d) {
                    return d.amount?Number(d.amount).toFixed(2):Number(0).toFixed(2);
                }
            },
            {field: 'priceSubtotal',width:120, title: '小计',
                templet: function(d) {
                    if(d.amount==undefined || d.price==undefined){return 0.00;}
                    return (d.amount*d.price).toFixed(2);
                },
            },
            {fixed: 'right', title: '操作', width: 80, align: 'center', toolbar: '#storageproductseditor'},
        ]],
        page: true,
        limit:50,
        height: 380
        , done: function (res, curr, count) {
            if(res.data.length>0){
                if(res.data[0].customerName!=undefined && res.data[0].companyDept!=undefined && res.data[0].bank!=undefined){
                    $("#editor-form input[name='customerName']").val(res.data[0].customerName);
                    let companyDept = res.data[0].companyDept;
                    $("#complaintUnit").val();
                    if($("#complaintUnit").val()==""){
                        $("#complaintUnit").append(new Option(companyDept, companyDept));
                        $("#complaintUnit").val(companyDept);
                    }
                    let bank = res.data[0].bank;
                    $("#issuingBank").val();
                    if($("#issuingBank").val()==""){
                        $("#issuingBank").append(new Option(bank, bank));
                        $("#issuingBank").val(bank);
                    }
                }
            }

            hoverOpenImg();//显示大图
            // for (let i in colourList) {
            //     $('.colourSelect').append(new Option(colourList[i].name, colourList[i].code));
            // }
            // for (let i in unitList) {
            //     $('.unitSelect').append(new Option(unitList[i].name, unitList[i].code));
            // }
            for (let i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                // $("#colour_" + tempId).val(res.data[i].colour);
                // $("#unit_" + tempId).val(res.data[i].unit);
            }
            form.render('select');
        }
    });

    table.on('edit(storageproductstable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "amount" || obj.field == "price" || obj.field == "priceSubtotal"|| obj.field == "cost") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        obj.update({
            priceSubtotal:(obj.data.amount*obj.data.price).toFixed(2)
        })
    });

    form.on("select(colourSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["colour"] = data.value;
            }
        });
    });
    form.on("select(unitSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["unit"] = data.value;
            }
        });
    });

    form.on("select(complaintUnitSelect)", function (data) {
        let complaintUnitCode = data.value;
        let selectCode = 0;
        if(id==""){
            selectCode=0;
        }
        bankSelect(complaintUnitCode,selectCode);
    });



    table.on('tool(storageproductstable)', function (obj) {
        if (obj.event === 'del') {
            layer.confirm('确认删除?', function (index) {
                let oldData =  table.cache["storageproductstableid"];
                for (let i = 0; i < oldData.length; i++) {
                    if (oldData[i].tempId == obj.data.tempId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('storageproductstableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });

        }
    });

    table.on('toolbar(storageproductstable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'exportcontract':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['75%', '75%'],
                    content: 'views/jsp/other/tpl/salescontractdetails.jsp'
                    // content: 'views/jsp/other/tpl/exportcontract.jsp'
                });
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.id);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？', function (index) {
                        let cbList = table.cache["storageproductstableid"];
                        for (let i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].id) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("storageproductstableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        }
        ;
    });

    function hoverOpenImg() {
        let img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            let img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

//---附件
    table.render({
        elem: '#attachment'
        , data: fileList
        , toolbar: '#attachmenttoolbar'
        , cellMinWidth: 220
        , cols: [[
            {field: 'wjName', title: '文件名称',style:"overflow:hidden"},
            // {field: 'fileName', title: '文件名称', fixed: true,style:"overflow:hidden"},
            {field: 'fileUrl', title: '文件路径',style:"overflow:hidden"},
            {field: 'fileType', title: '文件类型'},
            {field: 'fileSize', title: '文件大小(KB)'},
            {field: 'fileExecutor', title: '操作员',
                templet: function(data) {
                    let name = "";
                    $.each(executorList, function(index, item) {
                        if (data.fileExecutor==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            },
            {field: 'fileUploadTime', title: '上传时间',
                templet: function(d) {
                    return layui.util.toDateString(d.createTime,"yyyy-MM-dd");
                }
            },
            {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'},
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'ftp/uploadFile'
        , field: 'uploadify'
        , accept: 'file'
        , data:{"fileType":"CustomerComplaintFile"}
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var newfilename = "";
                if (ispd(wjCatalogCode, file.name)) {
                    // newfilename = getFileName(file.name);
                    // layer.msg("此目录下已存在重名的文件，已自动对本文件进行了重命名！");
                    layer.confirm('已存在同名的文件，是否覆盖？', function (index) {
                        layer.close(index);
                    });
                }
                if (newfilename != "") {
                    var obj = {};
                    obj.code = index;
                    obj.name = newfilename;
                    fileList.push(obj);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + newfilename + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var fileListIns = [];
                        for (var i = 0; i < fileList.length; i++) {
                            if (index != fileList[i].code) {
                                fileListIns.push(fileList[i]);
                            }
                        }
                        fileList = fileListIns;
                    });

                    $("#uploadlist").append(tr);
                }else{
                    var obj = {};
                    obj.code = index;
                    obj.name = file.name;
                    // fileList.push(obj);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var fileListIns = [];
                        for (var i = 0; i < fileList.length; i++) {
                            if (index != fileList[i].code) {
                                fileListIns.push(fileList[i]);
                            }
                        }
                        fileList = fileListIns;
                    });

                    $("#uploadlist").append(tr);
                }
            });
        }
        , done: function (res, index, upload) {
            var filename = "";
            for (var i = 0; i < uploadlist.length; i++) {
                if (uploadlist[i].code == index) {
                    filename = uploadlist[i].name;
                    break;
                }
            }
            if (res.data.length > 0) {
                var files = res.data;
                var filepaths = [];
                for (var i = 0; i < files.length; i++) {
                    var obj = {};
                    obj.fileName = files[i].fileName;
                    obj.ftpPath = files[i].ftpPath;
                    filepaths.push(obj);
                }
                if (savefile(filepaths, filename, wjCatalogCode)) {
                    let oldData = fileList;
                    let newData = [];
                    let num = oldData.length+1;
                    for(let i in files){
                        let newFile = {};
                        // fileList[i].tempId = num;
                        newFile.fileName = files[i].fileName;
                        newFile.wjName = files[i].originalFileName;
                        newFile.fileUrl = files[i].ftpPath;
                        newFile.fileSize = (this.files[index].size / 1024).toFixed(1);
                        newData.push(newFile);
                        num++;
                    }
                    oldData.push.apply(oldData, newData);
                    fileList = oldData;
                    table.reload('attachmenttableid', {data:fileList});
                }

                var tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            /* if (res.files.file) { //上传成功
                 var tr = $("#uploadlist").find('tr#upload-' + index)
                     , tds = tr.children();
                 tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                 tds.eq(3).html(''); //清空操作
                 return delete this.files[index]; //删除文件队列已经上传成功的文件
             }*/
            this.error(index, upload);
        }
        , error: function (index, upload) {
            let tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {}); //点击关闭刷新表格
                    }
                });
                break;
        };
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            downFileLoad(data.fileUrl+'/'+data.fileName);
        } else if (obj.event === 'del') {
            layer.confirm('确认删除吗？', function (index) {
                let oldData =  fileList;
                for (let i = 0; i < oldData.length; i++) {
                    if (oldData[i].tempId == obj.data.tempId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('attachmenttableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });

//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: logList
        , cols: [[
            {field: 'operationtype', title: '操作类型'}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    function isNumber(val) {
        let regPos = /^\d+(\.\d+)?$/; //非负浮点数
        let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }


    function queryById() {
        $.ajax({
            type: 'POST',
            url: 'complaint/selectByKey/' + id,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data) {
                        form.val("editor-form", {
                            "oddNumber": res.data.oddNumber,
                            "customerName": res.data.customerName,
                            "createTime": res.data.createTime,
                            "salesman": res.data.salesman,
                            "executor": res.data.executor,
                            "issuingBank": res.data.issuingBank,
                            "salesContractNo": res.data.salesContractNo,
                            "complaintUnit": res.data.complaintUnit,
                            "remark": res.data.remark,
                            "boxStatus": res.data.boxStatus,
                            "isEstablish": res.data.isEstablish,
                            "responsibleParty": res.data.responsibleParty,
                            "currency": res.data.currency,
                            "clientDeductionPrice": res.data.clientDeductionPrice,
                            "supplierDeductionPrice": res.data.supplierDeductionPrice,
                            "customerComplaintId": id
                        });
                        laydate.render({
                            elem: '#createTime',
                            type: 'date',
                            value: new Date(res.data.createTime),
                        });
                        let companyDept = res.data.complaintUnit;
                        if($("#complaintUnit").val()==""){
                            $("#complaintUnit").append(new Option(companyDept, companyDept));
                            $("#complaintUnit").val(companyDept);
                        }
                        bankSelect(companyDept,res.data.issuingBank);
                        productList = queryProductByCid(id);
                        table.reload('storageproductstableid',{data : productList});
                        fileList = queryFileByCid(id);
                        table.reload('attachmenttableid',{data : fileList});
                    } else {
                        layer.msg("初始化失败!");
                    }
                } else {
                    layer.msg("初始化失败!");
                }
            },
            error: function (data) {
                layer.msg("初始化失败!");
            }
        });
    }

//产品
    function queryProductByCid(cId) {
        let obj = [];
        $.ajax({
            type: 'POST',
            url: 'complaint/selectProductByCid/' + cId,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data.length > 0) {
                        obj = res.data;
                        form.val("editor-form", {
                            "productNo": res.data.productNo,
                            "specNo": res.data.specNo,
                            "normExplain": res.data.normExplain,
                            "chineseName": res.data.chineseName,
                            "englishName": res.data.englishName,
                            "chineseDesc": res.data.chineseDesc,
                            "englishDesc": res.data.englishDesc,
                            "unit": res.data.unit,
                            "colour": res.data.colour,
                            "price": res.data.price,
                            "amount": res.data.amount,
                            "priceSubtotal": res.data.priceSubtotal,
                            "customerArticleNo": res.data.customerArticleNo,
                        })
                    } else {
                        // layer.msg(res.msg, {icon : 0})
                    }
                } else {
                    layer.msg("产品初始化失败!");
                }
            },
            error: function (data) {
                layer.msg("产品初始化失败!");
            }
        });
        return obj;
    }

//附件
    function queryFileByCid(cId) {
        let obj = [];
        $.ajax({
            type: 'POST',
            url: 'complaint/selectFileByCid/' + cId,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data.length > 0) {
                        obj = res.data;
                        form.val("editor-form", {
                            "wjName": res.data.wjName,
                            // "fileName": res.data.fileName,
                            "fileUrl": res.data.fileUrl,
                            "fileType": res.data.fileType,
                            "fileSize": res.data.fileSize,
                            "fileExecutor": res.data.fileExecutor,
                            "fileUploadTime": res.data.fileUploadTime,
                        })
                    } else {
                        // layer.msg("暂无附件数据",{icon:3});
                    }
                } else {
                    layer.msg(res.msg, {icon: 3});
                }
            },
            error: function (data) {
                layer.msg("附件初始化失败!");
            }
        });
        return obj;
    }

//新增客诉
    function insert(data) {
        let tf = false;
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            url: 'complaint/insert',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    if (da.data) {
                        tf = true;
                        layer.msg("添加成功!");
                    } else {
                        layer.msg("添加失败!");
                    }
                } else {
                    layer.msg("请求失败!");
                }
            },
            error: function (data) {
                layer.msg("添加失败!");
            }
        });
        return tf;
    }

    function update(data) {
        let tf = false;
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            url: 'complaint/update',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    layer.msg(JSON.stringify(res));
                    tf = true;
                    layer.msg("修改成功!");
                } else {
                    layer.msg("修改失败!");
                }
            },
            error: function (data) {
                layer.msg("修改失败!");
            }
        });
        return tf;
    }

    $('#generateNumber').on('click', function () {
        let dataJson = {
            "type": "CC",
            // "time": time
        };
        $.ajax({
            type: 'POST',
            url: 'number/numberByTypeAndDate',
            data: JSON.stringify(dataJson),
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data != "") {
                        form.val("editor-form", {
                            "oddNumber": res.data,
                        })
                    }
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            },
            error: function (data) {
                layer.msg(data.msg, {icon: 5});
            }
        });
    });

    function downLoadFile(path) {

        let tf = false;
        $.ajax({
            type: 'post',
            data: {
                "path": JSON.stringify(path)
            },
            url: 'ftp/downloadfile',
            dataType: "json",
            // contentType: 'application/json',
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    tf = da.data == 0 ? false : true;

                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return tf;
    }

    function downLoad(fileName) {
        let xhr = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + fileName;
        xhr.open('GET', url, true);
        xhr.responseType = "blob";
        xhr.send(null);

        xhr.onload = function() {
            let aName = xhr.getResponseHeader('Content-Disposition').split('=')[1];

            const data = xhr.response;
            const a = document.createElement('a');
            const blob = new Blob([data],{ type: 'application/force-download' });
            const blobUrl = window.URL.createObjectURL(blob);
            download2(blobUrl,aName) ;
        }
    }

    function download2(blobUrl,aName){
        const a = document.createElement('a');

        a.style.display = 'none';
        a.download = decodeURIComponent(aName);
        a.href = blobUrl;
        a.click();
        document.body.removeChild(a);

    }
});

function bankSelect(code,selectCode){
    $("#issuingBank").empty();
    $.ajax({
        url: "bank/selectByCompanyCode",
        data: {"CompanyCode":code},
        success: function (res) {
            if (res.status == 200) {
                $.each(res.data, function (index, item) {
                    $("#issuingBank").append(new Option(item.bankname, item.bankcode));
                });
                issuingBankList = res.data;
                if(selectCode!=0){
                    $.each(issuingBankList, function (index, item) {
                        if (item.bankcode==selectCode){
                            $("#issuingBank").val(item.bankcode);
                        }
                    });
                    if($("#issuingBank").val()==""){
                        $("#issuingBank").append(new Option(selectCode, selectCode));
                        $("#issuingBank").val(selectCode);
                    }
                }
                form.render('select');
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

//获取文件目录下所有的文件名
function ispd(wjCatalogCode, filename) {
    /* fileNames=[];*/
    var cun = false;
    $.ajax({
        type: 'get',
        //  url : 'resource/getTree',
        data: {"wjCatalogCode": wjCatalogCode, "name": filename},
        url: 'wjinfo/ispd',
        dataType: "json",
        /*  contentType: 'application/json',*/
        async: false,
        success: function (da) {
            if (da.status == 200) {
                cun = da.data == 0 ? false : true;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return cun;
    // return obj;
}

function getFileName(filename) {
    /* fileNames=[];*/
    var cun = "";
    $.ajax({
        type: 'get',
        //  url : 'resource/getTree',
        data: {"filename": filename},
        url: 'wjinfo/getFileName',
        dataType: "json",
        /*  contentType: 'application/json',*/
        async: false,
        success: function (da) {
            if (da.status == 200) {
                cun = da.data;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return cun;
    // return obj;
}

//判断文件名是否重复
function iscf(filename) {
    var tf = false;
    for (var i = 0; i < fileNames.length; i++) {
        if (filename == fileNames[i]) {
            tf = true;
            break;
        }
    }
    return tf;
}

//保存上传的文件
function savefile(filepaths, filename, wjCatalogCode) {
    var tf = false;
    $.ajax({
        type: 'post',
        data: {
            "files": JSON.stringify(filepaths), "wjCatalogCode": JSON.stringify(wjCatalogCode),
            "name": JSON.stringify(filename)
        },
        url: 'wjinfo/savefile',
        dataType: "json",
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data == 0 ? false : true;
            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}